#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket_client_with_GUI_copilot.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/3/1 17:27 
"""

import tkinter as tk
from socket import socket, AF_INET, SOCK_STREAM
from socketserver import ThreadingMixIn
from threading import Thread
from typing import Optional


class SocketServer(ThreadingMixIn):
	def __init__(self, port: int):
		# 初始化socket
		self.server_socket = socket(AF_INET, SOCK_STREAM)
		# 绑定端口
		self.server_socket.bind(("", port))
		# 开始监听
		self.server_socket.listen(1)

	def receive_messages(self, text_widget: tk.Text):
		# 循环接收消息
		while True:
			# 接收客户端连接
			client_socket, _ = self.server_socket.accept()
			# 接收消息
			message = client_socket.recv(1024).decode()
			# 将消息添加到文本框
			text_widget.insert(tk.END, message + "\n")

	def close_socket(self):
		# 关闭socket
		self.server_socket.close()


class App:
	def __init__(self, root: tk.Tk):
		self.root = root
		self.root.title("Socket Message Receiver")

		# 创建端口配置框
		self.port_label = tk.Label(root, text="Listening Port:")
		self.port_label.grid(row=0, column=0, padx=5, pady=5)
		self.port_entry = tk.Entry(root)
		self.port_entry.grid(row=0, column=1, padx=5, pady=5)
		self.port_entry.insert(0, "8888")  # 默认端口为8888

		# 创建配置确认按钮
		self.config_button = tk.Button(
			root, text="Start Listening", command=self.start_listening
		)
		self.config_button.grid(row=0, column=2, padx=5, pady=5)

		# 创建监听结果显示区域
		self.result_text = tk.Text(root, height=10, width=50)
		self.result_text.grid(row=1, column=0, columnspan=3, padx=5, pady=5)

		# 创建清空结果输出按钮
		self.clear_button = tk.Button(
			root, text="Clear Results", command=self.clear_results
		)
		self.clear_button.grid(row=2, column=0, columnspan=3, padx=5, pady=5)

		# 创建SocketServer实例
		self.socket_server: Optional[SocketServer] = None

	def start_listening(self):
		# 获取端口号，如果没有输入则使用默认端口8888
		port = int(self.port_entry.get()) if self.port_entry.get() else 8888
		# 创建SocketServer实例
		self.socket_server = SocketServer(port)
		# 启动新线程用于接收消息
		receive_thread = Thread(
			target=self.socket_server.receive_messages, args=(self.result_text,)
		)
		receive_thread.start()

	def clear_results(self):
		# 清空结果显示区域
		self.result_text.delete(1.0, tk.END)

	def close_socket(self):
		# 如果socket_server实例存在，则关闭socket
		if self.socket_server:
			self.socket_server.close_socket()


root = tk.Tk()
app = App(root)
root.mainloop()
